const fs = require('fs');
const path = require('path');

const util = {
  // Clear folder
  emptyFolder (folderPath) {
    // Ensure the folder exists
    if (fs.existsSync(folderPath)) {
      // Get all files and subfolders in the folder
      const files = fs.readdirSync(folderPath);

      // Traverse the files and subfolders and delete them.
      files.forEach((file) => {
        const currentPath = path.join(folderPath, file);

        // If it is a file, delete it directly
        if (fs.lstatSync(currentPath).isFile()) {
          fs.unlinkSync(currentPath);
        }
        // If it is a folder, emptyFolder is called recursively
        else if (fs.lstatSync(currentPath).isDirectory()) {
          util.emptyFolder(currentPath);
        }
      });
      // Delete empty folders
      fs.rmdirSync(folderPath);
      console.log(`Folder ${folderPath} was successfully emptied.`);
    } else {
      console.log(`Folder ${folderPath} does not exist.`);
    }
  },
  // Delete compressed files
  deleteZipFile (filePath) {
    // Make sure the file exists
    if (fs.existsSync(filePath)) {
      // Delete files
      fs.unlinkSync(filePath);
      console.log(`Compressed file ${filePath} was successfully deleted.`);
    } else {
      console.log(`Compressed file ${filePath} does not exist.`);
    }
  },
  // Read the contents of the workspace file
  readFileInWorkspace (fileName) {
    // Get the root directory of the workspace
    const workspaceRoot = path.join('../')
    if (workspaceRoot) {
      // Build file path
      const filePath = path.join(workspaceRoot, fileName);
      try {
        // Read file content
        const fileContent = fs.readFileSync(filePath, 'utf-8');
        // Display the file contents in the output window.
        return fileContent
      } catch (error) {
        console.error(`Error reading file ${fileName}: ${error.message}`);
      }
    } else {
      console.log('No workspace opened.')
    }
  }
};

module.exports = util;